package com.ttms.web.common;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.google.gson.Gson;
import com.ttms.pojo.User;
import com.ttms.service.UserService;
import com.ttms.service.impl.UserServiceImpl;
import com.ttms.utils.WebUtils;

import java.util.HashMap;
import java.util.Map;
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数username
        String username = req.getParameter("username");
        // 调用userService.existsUsername();
        boolean existsUsername = userService.existsUsername(username);
        // 把返回的结果封装成为map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existsUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    /**
        Gson gson = new Gson();
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、销毁Session中用户登录的信息（或者销毁Session）
        req.getSession().invalidate();
//        2、重定向到首页（或登录页面）。
        resp.sendRedirect(req.getContextPath());
    }
    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        User loginUser = userService.login(new User(null, null, password, phone,0,null));
        System.out.println(loginUser);
        if(loginUser == null){
            System.out.println("账号名或密码错误");
            req.setAttribute("msg","账号名或密码错误");
            req.setAttribute("phone",phone);
            req.setAttribute("password",password);
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else {
            System.out.println("登录成功");
            req.setAttribute("msg", "登录成功！！！");
            req.setAttribute("username", loginUser.getUsername());
            req.setAttribute("phone", loginUser.getPhone());
            if (loginUser.getType()==1){
                req.getSession().setAttribute("user", loginUser);
                resp.sendRedirect("/ttms/manage/playServlet?action=page");
            }else {
                req.getSession().setAttribute("user", loginUser);
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            }
        }
    }

    /**
     * 处理注册的功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取Session中的验证码
        String token = (String) req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        // 删除 Session中的验证码
        req.getSession().removeAttribute("");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String repwd = req.getParameter("repwd");
        String phone = req.getParameter("phone");
        String code = req.getParameter("code");
        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());
        if(token.equalsIgnoreCase(code)){
            if(userService.existsUsername(username)){
                System.out.println("用户名 [ "+ username +" ]已存在");
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username", username);
                req.setAttribute("password",password);
                req.setAttribute("repwd",repwd);
                req.setAttribute("phone",phone);
                req.setAttribute("code",code);
                req.getRequestDispatcher("/regist.jsp").forward(req,resp);
            }
            else if (!password.equals(repwd)){
                System.out.println("两次输入的密码"+ password + "和" + repwd + "不一致");
                req.setAttribute("msg","两次输入的密码不一致");
                req.setAttribute("username",username);
                req.setAttribute("password",password);
                req.setAttribute("repwd",repwd);
                req.setAttribute("phone",phone);
                req.getRequestDispatcher("/regist.jsp").forward(req,resp);
            }
            else {
                User loginUser = new User(null,username, password , phone, 0,null);
                userService.registUser(loginUser);
                req.getSession().setAttribute("user", loginUser);
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }

        }else {
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", username);
            req.setAttribute("password", password);
            req.setAttribute("phone", phone);
            req.setAttribute("code", code);
            System.out.println("验证码 [" + code + "] 错误");
            req.getRequestDispatcher("/regist.jsp").forward(req, resp);
        }
    }

}

